import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Checkbox, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, Link, SelectLang, useModel } from 'umi';
import Footer from '@/components/Footer';
import { login, queryHospitalAttestation } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import md5 from 'js-md5';
import loginB from '../../../../public/loginB.png'
import styles from './index.less';
import { Color } from '@antv/l7-react/lib/component/LayerAttribute';
import { getCode, loginMent, getAccessToken, bindUserPhone, getBindUser } from '../register/service';
import { articlepp } from '../../doctor/service';


const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

const Login: React.FC = () => {
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
    const [type, setType] = useState<string>('account');
    const { initialState, setInitialState } = useModel('@@initialState');
    const intl = useIntl();
    const [on, setOn] = useState(false);
    const [weixinLogin, setweixinLogin] = useState(false);
    const [phone, setPhone] = useState('');
    const [phoneTwo, setPhoneTwo] = useState('');
    const [code, setCode] = useState('');
    const [codeTwo, setCodeTwo] = useState('');
    const [OpenIdppp, setOpenIdppp] = useState('');
    const [agreeToTerms, setAgreeToTerms] = useState(false);
    const [isCodeSent, setIsCodeSent] = useState(false);
    const [countdown, setCountdown] = useState(60);
    const myDivRef = useRef(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [contentValue, setContentValue] = useState('');
    const [appid, setAppid] = useState('wxd953a4c87e26d663');  //  wxaa6be8148f8526bc (测试)   
    const [openIdValue, setopenIdValue] = useState('');

    let openIdPPP = '';
    const lightOn = () => {
        setOn(true)
        const obj = new window.WxLogin({
            self_redirect: true,
            id: 'myDivRef',
            appid: appid, // 测试
            scope: 'snsapi_login',
            redirect_uri: 'https://d.yizhongxin.com.cn/oauth/WxLogin.html',
            // redirect_uri: 'https://d-stage.yizhongxin.com.cn/oauth/WxLogin.html', //测试
            state: 'STATE',
            style: "block",
            href: "https://d.yizhongxin.com.cn/oauth/WxLogin.css"
        });
    }
    const lightOff = () => {
        setOn(false)
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const Getarticle = async (id: any) => {
        const response = await fetch(`/api/cmsArticle/${id}`, {
            method: 'get',
            headers: {
                'Content-Type': 'application/json',
            },
            // body: JSON.stringify({ id }),
        });
        const json = await response.json();
        setContentValue(json.data.content)
        setIsModalOpen(true)
    }
    const debounce = (func, delay = 300) => {
        let timeoutId;
        return (...args) => {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                func.apply(this, args);
            }, delay);
        };
    };
    const codeData = debounce((codeValue: any) => {
        getAccessToken({ appid: appid, code: codeValue })
            .then(msg => {
                if (msg.code === 200) {
                    // openIdPPP = msg.data.openId
                    console.log(msg.data,'[[[[[')
                    if(!msg.data){
                        setweixinLogin(true);
                    }else {
                        openIdPPP = msg.data.openId
                        // eslint-disable-next-line @typescript-eslint/no-use-before-define
                        getBindUserMent()
                    }
                } 
            })
            .catch(error => {
                console.error('Error fetching access token:', error);
            });
    }, 1000)

    const getCodeData = async () => {
        const msg = await getCode({ phone: phone });
        if (msg.code === 200) {
            setIsCodeSent(true);
            startCountdown();
            message.success('发送成功');
        } else {
            message.error(msg.msg);
        }
    }
    const getCodeDataTwo = async () => {
        const msg = await getCode({ phone: phoneTwo });
        if (msg.code === 200) {
            setIsCodeSent(true);
            startCountdown();
            message.success('发送成功');
        } else {
            message.error(msg.msg);
        }
    }
    const startCountdown = () => {
        const interval = setInterval(() => {
            setCountdown((prevCount) => prevCount - 1);
        }, 1000);
        setTimeout(() => {
            clearInterval(interval);
            setIsCodeSent(false);
            setCountdown(60);
        }, 60000);
    };
    const handleVerificationCodeChange = (event: any) => {
        setPhone(event.target.value);
    };
    const handleVerificationCodeChangeTwo = (event: any) => {
        setPhoneTwo(event.target.value);
    };
    const codeChange = (event: any) => {
        setCode(event.target.value);
    };
    const codeChangeTwo = (event: any) => {
        setCodeTwo(event.target.value);
    };
    // const getGogin = async () => {
    //     if (!agreeToTerms) {
    //         message.warning('请勾选《用户协议》和《隐私政策》');
    //         return false
    //     }
    //     if (phone == '') {
    //         message.warning('请填写手机号');
    //         return false
    //     }
    //     if (code == '') {
    //         message.warning('请填写验证码');
    //         return false
    //     }
    //     const msg = await loginMent({
    //         phone: phone,
    //         smsCode: code
    //     })
    //     if (msg.code === 200) {
    //         console.log('[[[[[[[[[[[[[[[[')
    //         history.push('/welcome');
    //         // localStorage.setItem('username', JSON.stringify(msg.data));
    //         // const defaultLoginSuccessMessage = intl.formatMessage({
    //         //     id: 'pages.login.success',
    //         //     defaultMessage: '登录成功！',
    //         // });
    //         // message.success(defaultLoginSuccessMessage);
    //         // window.location.href = `${window.location.origin}/operations/special-detail?id=22`
    //     } else {
    //         message.warning(msg.msg);
    //     }
    //     // if (msg.code === 200) {
    //     //     sessionStorage.clear();
    //     //     console.log(
    //     //         'login sessionStorage.getItem(`hosiptaAuthlId`)',
    //     //         sessionStorage.getItem(`hosiptaAuthlId`),
    //     //     );
    //     //     const defaultLoginSuccessMessage = intl.formatMessage({
    //     //         id: 'pages.login.success',
    //     //         defaultMessage: '登录成功！',
    //     //     });
    //     //     message.success(defaultLoginSuccessMessage);
    //     //     msg.currentAuthority = 'admin';
    //     //     sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
    //     //     await fetchUserInfo();
    //     //     // console.log('hospitalMsg1111', msg.data.adminType == 2);
    //     //     /** 此方法会跳转到 redirect 参数所在的位置 */
    //     //     if (!history) return;
    //     //     //console.log('hospitalMsg', msg.data.adminType == 2);
    //     //     if (msg.data.adminType == 2) {
    //     //         const hospitalMsg = await queryHospitalAttestation();
    //     //         // console.log('hospitalMsg', hospitalMsg.data.status == 1);
    //     //         if (hospitalMsg.data == null) {
    //     //             sessionStorage.setItem(`hosiptaAuthlId`, 0);
    //     //             sessionStorage.setItem(`hosiptalId`, 0);
    //     //             sessionStorage.setItem(`hospitalStatus`, -1);
    //     //             history.push('/setting/hospital');
    //     //         } else {
    //     //             if (hospitalMsg.data.status == 0 || hospitalMsg.data.status == 2) {
    //     //                 sessionStorage.setItem(`hosiptaAuthlId`, 0);
    //     //             } else {
    //     //                 sessionStorage.setItem(`hosiptaAuthlId`, hospitalMsg.data.hospitalId);
    //     //             }
    //     //             sessionStorage.setItem(`hosiptalId`, hospitalMsg.data.hospitalId);
    //     //             sessionStorage.setItem(`hospitalName`, hospitalMsg.data.name);
    //     //             sessionStorage.setItem(`hospitalStatus`, hospitalMsg.data.status);
    //     //             if (hospitalMsg.data.status == 1) {
    //     //                 history.push('/welcome');
    //     //             } else {
    //     //                 history.push('/setting/hospital');
    //     //             }
    //     //         }
    //     //         return;
    //     //     } else {
    //     //         const { query } = history.location;
    //     //         const { redirect } = query as { redirect: string };
    //     //         history.push(redirect || '/');
    //     //         return;
    //     //     }
    //     // }

    // }
    const fetchUserInfo = async () => {
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };
    const lijibangding = async () => {
        const msg = await bindUserPhone({
            openId: openIdValue,
            phone: phoneTwo,
            smsCode: codeTwo
        })
        if (msg.code === 200) {
            sessionStorage.clear();
            console.log(
                'login sessionStorage.getItem(`hosiptaAuthlId`)',
                sessionStorage.getItem(`hosiptaAuthlId`),
            );
            const defaultLoginSuccessMessage = intl.formatMessage({
                id: 'pages.login.success',
                defaultMessage: '登录成功！',
            });
            message.success(defaultLoginSuccessMessage);
            msg.currentAuthority = 'admin';
            sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
            await fetchUserInfo();
            // console.log('hospitalMsg1111', msg.data.adminType == 2);
            /** 此方法会跳转到 redirect 参数所在的位置 */
            if (!history) return;
            //console.log('hospitalMsg', msg.data.adminType == 2);
            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            history.push(redirect || '/');
            return;
        } else {
            setUserLoginState(msg);
        }
    }
    const getBindUserMent = async () => {
        setopenIdValue(openIdPPP)
        const msg = await getBindUser({ openId: openIdPPP })
        if (msg.msg == '承载数据为空') {
            setweixinLogin(true);
            return false
        }
        if (msg.code === 200) {
            sessionStorage.clear();
            console.log(
                'login sessionStorage.getItem(`hosiptaAuthlId`)',
                sessionStorage.getItem(`hosiptaAuthlId`),
            );
            const defaultLoginSuccessMessage = intl.formatMessage({
                id: 'pages.login.success',
                defaultMessage: '登录成功！',
            });
            message.success(defaultLoginSuccessMessage);
            msg.currentAuthority = 'admin';
            sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
            await fetchUserInfo();
            // console.log('hospitalMsg1111', msg.data.adminType == 2);
            /** 此方法会跳转到 redirect 参数所在的位置 */
            if (!history) return;
            //console.log('hospitalMsg', msg.data.adminType == 2);
            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            history.push(redirect || '/');
            return;
        } else {
            setweixinLogin(true)
        }
    }
    window.addEventListener('message', (event) => {
        try {
            console.log(event.data.code, '[[aaaaaaaaaaaaaa')
            codeData(event.data.code)
        } catch {

        }
        event.data
        // console.log('Received message from iframe:', event.data);
        // 在这里处理接收到的消息
    });
    const getGogin = async (values: API.LoginParams) => {
        try {
            if (!agreeToTerms) {
                message.warning('请勾选《用户协议》和《隐私政策》');
                return false
            }
            if (phone == '') {
                message.warning('请填写手机号');
                return false
            }
            if (code == '') {
                message.warning('请填写验证码');
                return false
            }
            // 登录
            const msg = await loginMent({
                phone: phone,
                smsCode: code
            });
            console.log('msg----', msg);
            if (msg.code === 200) {
                sessionStorage.clear();
                console.log(
                    'login sessionStorage.getItem(`hosiptaAuthlId`)',
                    sessionStorage.getItem(`hosiptaAuthlId`),
                );
                const defaultLoginSuccessMessage = intl.formatMessage({
                    id: 'pages.login.success',
                    defaultMessage: '登录成功！',
                });
                message.success(defaultLoginSuccessMessage);
                msg.currentAuthority = 'admin';
                sessionStorage.setItem(`currentUser`, JSON.stringify(msg.data));
                await fetchUserInfo();
                // console.log('hospitalMsg1111', msg.data.adminType == 2);
                /** 此方法会跳转到 redirect 参数所在的位置 */
                if (!history) return;
                //console.log('hospitalMsg', msg.data.adminType == 2);
                const { query } = history.location;
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            }

            // 如果失败去设置用户错误信息
            setUserLoginState(msg);
        } catch (error) {
            console.log('error', error);
            // const defaultLoginFailureMessage = intl.formatMessage({
            //   id: 'pages.login.failure',
            //   defaultMessage: '登录失败，请重试！',
            // });
            // message.error(defaultLoginFailureMessage);
        }
    };
    const { status, type: loginType } = userLoginState;

    return (
        <div>
            <Modal open={isModalOpen} footer={null} className='batchModal' width={1000} style={{ height: '80vh', overflowY: 'auto' }}
                onCancel={handleCancel} >
                <div dangerouslySetInnerHTML={{ __html: contentValue }} />
            </Modal>
            {
                <div>
                    <div className={weixinLogin ? styles.hiddenTwo : styles.hidden}>
                        <div className={styles.shoujih} >
                            <div className={styles.inpyyTwo}>
                                <div className={styles.bangding}>手机号绑定</div>
                                <div className={styles.bangdingTwo}>为防止帐号丢失以及方便找回，建议你绑定手机号码后再使用</div>
                                <input className={styles.inputOnePP} type="text" placeholder='请输入手机号' value={phoneTwo} onChange={handleVerificationCodeChangeTwo} />
                                <div className={styles.inputTwoII}>
                                    <input type="text" value={codeTwo} placeholder='请输入验证码' onChange={codeChangeTwo} />
                                    {
                                        !isCodeSent ? <div className={styles.getCodeTwo} onClick={getCodeDataTwo}>获取验证码</div> :
                                            <div className={styles.getCodeTwo} style={{ backgroundColor: '#92e0c8' }} >{countdown}s后获取验证码</div>
                                    }
                                </div>

                            </div>
                            <div className={styles.dengluLLL} onClick={lijibangding}>立即绑定</div>
                        </div>
                    </div >
                    <div className={weixinLogin ? styles.hidden : styles.container}>
                        <div className={styles.yishengban}>医中心 · 医生版</div>
                        <div className={styles.loginBox}>
                            <div className={styles.topdeng}>
                                <div className={on ? styles.xuanzhong : styles.xuanzhongTwo} onClick={lightOn}>微信登录</div>
                                <div className={on ? styles.xuanzhongTwo : styles.xuanzhong} onClick={lightOff}>验证码登录</div>
                            </div>

                            <div className={!on ? '' : styles.hidden} >
                                <div className={styles.inpyy}>
                                    <input className={styles.inputOne} type="text" placeholder='请输入手机号' value={phone} onChange={handleVerificationCodeChange} />
                                    <div className={styles.inputTwo}>
                                        <input type="text" value={code} placeholder='请输入验证码' onChange={codeChange} />
                                        {
                                            !isCodeSent ? <div className={styles.getCode} onClick={getCodeData}>获取验证码</div> :
                                                <div className={styles.getCode} style={{ backgroundColor: '#92e0c8' }} >{countdown}s后获取验证码</div>
                                        }
                                    </div>
                                    <div className={styles.psiah}> <input
                                        type="checkbox"
                                        checked={agreeToTerms}
                                        onChange={() => setAgreeToTerms(!agreeToTerms)}
                                    /><span>我已阅读并同意 <span style={{ color: '#62C9A9' }} onClick={() => Getarticle(23)}>《用户协议》</span>和 <span style={{ color: '#62C9A9' }} onClick={() => Getarticle(24)} >《隐私政策》</span></span></div>
                                </div>
                                <div className={styles.denglu} onClick={getGogin}>登录</div>

                            </div>
                            <div className={!on ? styles.hidden : ''} style={{ position: 'relative' }}>
                                <div style={{ width: '400px', height: '400px', position: 'absolute', left: '15px', top: '40px' }} id='myDivRef' />
                            </div>
                        </div>
                        <div className={styles.fottre}>京ICP备2023005250号-4</div>
                    </div >
                </div>
            }
        </div >
    );
};

export default Login;
